from functools import wraps
from rich.console import Console
from rich.table import Table,Column

from config import get_config
from .create_summary import create_summary
from .row_utils import create_row

console = Console()

def format_print(func):
    @wraps(func)
    def wrapper(*args,**kwargs):
        result = func(*args,**kwargs)
        print_table(result)
        print_summary(result)
        conf = get_config()
        config = dict(conf)
        output_file = config.get('output_file')
        if output_file is not None:
            output_to_file(output_file,result)
        return result
    return wrapper

# 打印table
def print_table(mlist):
    table = Table(title="匹配结果"
                  ,show_lines=True, expand=True,show_header=True)
    table.add_column("文件",justify="left",header_style='yellow')
    table.add_column("匹配项",justify="left",header_style='yellow')
    table.add_column("匹配值",justify="left",header_style='yellow')

    t_list = []
    for item in mlist:
       i_list = create_row(item)
       t_list.extend(i_list)


    for row in t_list:
        table.add_row(row['file'],row['reg'],row['target'])

    console.print(table)




def print_summary(mlist):
    msg = create_summary(mlist)
    console.print(msg, style='green')

def output_to_file(filename,rlist):
    match_ = [item for item in rlist if len(item['match']) > 0]


    with open(filename,'wb') as file:
        for p_item in match_:
            file.write((p_item['file']+'\n').encode('utf-8'))
            for item in p_item['match']:
                file.write(item['target'].encode('utf-8'))
            file.write('\n'.encode('utf-8'))




